﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using Castle.Core.Internal;

namespace MPICore
{
    public class EnumCenter
    {
        public static string GetDescription(object value, string unknownDescription = "")
        {
            if (value ==null)
            {
                return !string.IsNullOrEmpty(unknownDescription) ? unknownDescription : string.Empty;
            }

            var field = value.GetType().GetField(value.ToString());
            if (field == null)
            {
                return !string.IsNullOrEmpty(unknownDescription) ? unknownDescription : string.Empty;
            }

            var attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;

            return attribute == null?value.ToString():attribute.Description;
        }

        public static string GetDescription<T>(int? value, string unknownDescription)
        {
            if (value == null)
            {
                return !string.IsNullOrEmpty(unknownDescription) ? unknownDescription : string.Empty;
            }

            return GetDescription((T)Enum.Parse(typeof(T), value.Value.ToString()), unknownDescription);
        }

        public static string GetDescription<T>(string value, string unknowDescription)
        {
            if (value==null)
            {
                return !string.IsNullOrEmpty(unknowDescription) ? unknowDescription : string.Empty;
            }

            if (!Enum.GetNames(typeof(T)).Contains(value))
            {
                return value;
            }

            return GetDescription((T) Enum.Parse(typeof(T), value), unknowDescription);
        }

        public static Dictionary<int, string> GetDictionaryForEnum<T>()
        {
            Dictionary<int, string> dics = new Dictionary<int, string>();
            foreach (var v in Enum.GetValues(typeof(T)))
            {
                dics.Add((int)v,GetDescription(v));
            }

            return dics;
        }

        public static int GetValueForEnum<T>(string desctiption)
        {
            int value = 0;
            foreach (var item in Enum.GetValues(typeof(T)))
            {
                if (GetDescription(item)==desctiption)
                {
                    return (int) item;
                }
            }

            return value;
        }

        

        public enum PhoneNumberType
        {
            /// <summary>
            /// 移动手机
            /// </summary>
            [Description("移动手机")]
            V1_Mobile=1,
            /// <summary>
            /// 家庭电话
            /// </summary>
            [Description("家庭电话")]
            v2_Home=2,
            /// <summary>
            /// 公司电话
            /// </summary>
            [Description("公司电话")]
            V3_Company =3
        }
    }
}
